<template>
    <el-select v-model="formData" placeholder="请选择" clearable @change="dataChange">
        <el-option
            v-for="dict in dsOptions"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
    </el-select>    
</template>

<script setup>
import useDictStore from '@/store/modules/dict';
import { dsData } from "@/api/dev/modelData";

const emit = defineEmits(['update'])

const formData = ref(null);
const dsOptions = ref([]);

const props = defineProps({
  modelValue: [String, Number, Array],
  // 数据集
  dsCode: {
    type: String,
    required: true,
  },
  // 展示方式
  formType: {
    type: String,
    default: 'select',
  }
});

watch(() => props.modelValue, val => {
  formData.value = val;
},{ deep: true, immediate: true });


watch(() => props.dsCode, val => {
  if(val != null){
    loadDs(val)
  }else{
    treeOptions.value = [];
  }
},{ deep: true, immediate: true });
    
function loadDs(dsCode) {
    let dsKey = "ds_"+dsCode;
    const dicts = useDictStore().getDict(dsKey);
    if (dicts) {
        dsOptions.value = dicts;
    } else {
        dsData(dsCode).then(resp => {
            dsOptions.value = resp.data;
            useDictStore().setDict(dsKey, resp.data);
        });
    }
}

function dataChange() {    
  if(props.formType == 'muilt'){
    emit("update:modelValue", formData.value.join(props.separator));
    }else{
    emit("update:modelValue", formData.value);
    }
}
</script>

<style scoped>
.el-tag + .el-tag {
  margin-left: 10px;
}
</style>
